#include <EB0/EB0.h>

namespace EB0
{
namespace States
{
#pragma region Constructor / Destructor
	// Constructor
	ThePlace::ThePlace()
	{
		// Null pointers
		mPlayer = 0;
		mSeekBot = 0;
		mThePlaceBGM = 0;
	}

	// Destructor
	ThePlace::~ThePlace()
	{
		// Null pointers
		mPlayer = 0;
		mSeekBot = 0;
		mThePlaceBGM = 0;
	}
#pragma endregion

#pragma region Load / Unload
	// Load resources
	void ThePlace::load(Window::RenderWindow* window)
	{
		// Load new music
		mThePlaceBGM = Managers::AudioManager::getSingletonPtr()->createMusic("music/023- Earthbound - Home Sweet Home.ogg");

		// Load the world
		loadWorld(window);

		// Create entities
		mPlayer = new Entities::Player();
		mSeekBot = new Entities::SeekBot();
	}

	// Unload resources
	void ThePlace::unload(Window::RenderWindow* window)
	{
		// Destroy entities
		if (mPlayer)
		{
			delete mPlayer;
			mPlayer = 0;
		}

		if (mSeekBot)
		{
			delete mSeekBot;
			mSeekBot = 0;
		}

		// Unload slideshow
		unloadWorld(window);

		// Unload any previous music
		if (mThePlaceBGM)
			Managers::AudioManager::getSingletonPtr()->destroyMusic(mThePlaceBGM);
	}
#pragma endregion

#pragma region Create / Destroy Scene
	// Create scene
	void ThePlace::createScene(Window::RenderWindow* window)
	{
		// Play music
		if (mThePlaceBGM)
		{
			mThePlaceBGM->Play();
			mThePlaceBGM->SetLoop(true);
		}

		// Set the background colour of the window to a faded white
		if (window)
			window->setClearColor(246, 246, 246);

		// Create world scene
		createWorldScene(window);

		// Attach entities
		attachEntity("Player", mPlayer);
		b2Vec2 playerPos(32, 32); // arbitrary point away from the origin
		mPlayer->getBody()->SetXForm(playerPos, mPlayer->getBody()->GetAngle());

		attachEntity("SeekBot", mSeekBot);
		b2Vec2 seekBotPos(16, 48); // arbitrary point away from the origin
		mSeekBot->getBody()->SetXForm(seekBotPos, mSeekBot->getBody()->GetAngle());
	}

	// Destroy scene
	void ThePlace::destroyScene(Window::RenderWindow* window)
	{
		// Destroy entities
		if (mPlayer)
			removeEntity(mPlayer);

		if (mSeekBot)
			removeEntity(mSeekBot);

		// Unload world scene
		destroyWorldScene(window);

		// Stop music
		if (mThePlaceBGM)
			mThePlaceBGM->Stop();
	}
#pragma endregion

#pragma region Update State
	// Update state
	void ThePlace::update(Window::RenderWindow* window, float dt)
	{
		// Update world, switch to world state if no slides remain
		updateWorld(window, dt);

		// Update camera to follow the player
		Entities::Entity* playerEntity = fetchEntity("Player");

		if (playerEntity)
			getWorldLayer()->SetCenter(playerEntity->getBody()->GetPosition().x * TILE_SIZE, playerEntity->getBody()->GetPosition().y * TILE_SIZE);
	}
#pragma endregion
} // namespace States
}